package cn.xorange.commons.datasource.configuration;

import cn.xorange.commons.datasource.constants.DataDefaultConstants;
import cn.xorange.commons.datasource.service.MyBatisMapWrapperFactory;
import cn.xorange.commons.exception.DataException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@Slf4j
//@Configuration
//@AutoConfigureBefore({MybatisAutoConfiguration.class})
//@MapperScan(value = {
//        "**.mapper"
//})
public class MyBatisConfig {

    @Resource
    MyBatisProperties properties;

    @Bean
    //@ConfigurationProperties("mybatis.configuration")
    public org.apache.ibatis.session.Configuration defaultMyBatisConfig(){
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //实体类至数据库转下划线
        configuration.setMapUnderscoreToCamelCase(properties.mapUnderscoreToCamelCase);
        configuration.setCallSettersOnNulls(true);
        configuration.setReturnInstanceForEmptyRow(true);
        //configuration.setLogImpl(StdOutImpl.class); //打印sql
        log.debug("Initializing [defaultMyBatisConfig]");
        return configuration;
    }


    /***
     * 自定义会话工厂
     * @return :自定义的会话工厂
     */
    @Primary
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        /**
            String typeAliasesPackage = env.getFieldName("mybatis.typeAliasesPackage");
            typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
            VFS.addImplClass(SpringBootVFS.class);
         **/
        /** org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.class */
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(properties.dataSourceConfig.dynamicDataSource());
        /** sessionFactory.setTypeAliasesPackage(typeAliasesPackage); **/
        sessionFactory.setConfiguration(defaultMyBatisConfig());
        sessionFactory.setObjectWrapperFactory(new MyBatisMapWrapperFactory());
        String mappers = properties.mapperLocations;
        //if (mappers.isEmpty()){
        //    mappers = DataDefaultConstants.MYBATIS_MAPPER_LOCATIONS;
        //}
        sessionFactory.setMapperLocations(properties.resolveMapperLocations(mappers.split(",") ));

        log.debug("Initializing [sqlSessionFactory]");
        return sessionFactory.getObject();
    }



    /**
    private PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        //是否将参数offset作为PageNum使用
        properties.setProperty("offsetAsPageNum", "false");
        properties.setProperty("rowBoundsWithCount", "false");
        properties.setProperty("pageSizeZero", "true");
        //是否进行count查询
        //properties.setProperty("rowBoundsWithCount", "true");
        // 注意的是reasonable参数，表示分页合理化，默认值为false。
        //如果该参数设置为 true 时，pageNum<=0 时会查询第一页，pageNum>pages（超过总数时），会查询最后一页。默认false 时，直接根据参数进行查询。
        properties.setProperty("reasonable", "false");
        properties.setProperty("returnPageInfo", "none");
        //处理多数据源数据库
        properties.setProperty("autoRuntimeDialect", "true");
        //数据库类型
        //properties.setProperty("helperDialect", "mysql");
        properties.setProperty("params","pageNum=pageNum;pageSize=pageSize;");
        //根据入参自动开启分页
        properties.setProperty("supportMethodsArguments", "true");
        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }
     */

}
